package co.fitstart.admin.web.controller.user;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.demo2do.core.support.Page;
import com.demo2do.core.support.Result;
import com.demo2do.core.utils.JsonUtils;
import com.demo2do.core.web.utils.WebUtils;

import co.fitstart.admin.entity.search.CourseRoundFeedbackSearch;
import co.fitstart.admin.entity.security.Login;
import co.fitstart.admin.service.CourseRoundService;
import co.fitstart.admin.service.PrincipalService;
import co.fitstart.admin.service.SiteService;
import co.fitstart.admin.web.interceptor.MenuSetting;
import co.fitstart.admin.web.resolver.Secure;
import co.fitstart.admin.web.view.ExcelTemplateView;
import co.fitstart.entity.course.round.CourseRoundFeedback;
import co.fitstart.entity.principal.Principal;
import co.fitstart.entity.site.Site;
import co.fitstart.entity.utils.DateFormatUtils;

/**
 * 课程吐槽
 * @author haiyan_xiao
 *
 */
@Controller
@RequestMapping("courseround-feedbacks")
@MenuSetting("menu-user")
public class CourseRoundFeedbackController {

    private static final Logger logger = LoggerFactory.getLogger(CourseRoundFeedbackController.class);

    @Autowired
    private SiteService siteService;

    @Autowired
    private PrincipalService principalService;

    @Autowired
    private CourseRoundService courseRoundService;

    /**
     * 
     * @param login
     * @param siteId
     * @param handled
     * @param page
     * @return
     */
    @RequestMapping(value = "", method = RequestMethod.GET)
    @MenuSetting("submenu-courseround-feedback-management")
    public ModelAndView list(@Secure Login login,
                             @RequestParam(value = "siteId", required = false) Long siteId,
                             @RequestParam(value = "handled", required = false) Boolean handled,
                             Page page) {
        ModelAndView modelAndView = new ModelAndView("user/feedback/courseround-feedback-list");
        
        Site site = null;
        if(siteId != null) {
            site = siteService.load(siteId);
        }
        
        List<CourseRoundFeedback> feedbacks = new ArrayList<>();
        
        if(login.isRoot() || login.isAdmin()) {
            feedbacks = courseRoundService.listCourseRoundFeedback(site, handled, page);
        } else if(login.isAreaManager() || login.isAreaServer()) {
            Principal principal = principalService.load(Principal.class, login.getId());
            
            List<Site> sites = siteService.listSite(principal);
            
            if(!sites.isEmpty()) {
                if(site == null) {
                    feedbacks = courseRoundService.listCourseRoundFeedback(sites, handled, page);
                } else if(sites.contains(site)) {
                    feedbacks = courseRoundService.listCourseRoundFeedback(site, handled, page);
                }
            }
        } else {
            feedbacks = courseRoundService.listCourseRoundFeedback(login.getSite(), handled, page);
        }
        
        modelAndView.addObject("siteId", siteId);
        modelAndView.addObject("handled", handled);
        modelAndView.addObject("feedbacks", feedbacks);
        
        return modelAndView;
    }

    /**
     * 
     * @param feedbackId
     * @return
     */
    @RequestMapping(value = "/{feedbackId}", method = RequestMethod.GET)
    @MenuSetting("submenu-courseround-feedback-management")
    public ModelAndView view(@PathVariable("feedbackId") Long feedbackId) {
        ModelAndView modelAndView = new ModelAndView("user/feedback/courseround-feedback-view");
        
        CourseRoundFeedback feedback = courseRoundService.loadCourseRoundFeedback(feedbackId);
        modelAndView.addObject("feedback", feedback);
        
        return modelAndView;
    }

    /**
     * 
     * @param feedbackId
     * @return
     */
    @RequestMapping(value = "/{feedbackId}/handle", method = RequestMethod.GET)
    @MenuSetting("submenu-courseround-feedback-management")
    public ModelAndView handle(@PathVariable("feedbackId") Long feedbackId) {
        ModelAndView modelAndView = new ModelAndView("user/feedback/courseround-feedback-handle");
        
        modelAndView.addObject("feedbackId", feedbackId);
        
        return modelAndView;
    }

    /**
     * 
     * @param login
     * @param feedbackId
     * @param remark
     * @return
     */
    @RequestMapping(value = "/{feedbackId}/handle", method = RequestMethod.PATCH)
    public @ResponseBody String onHandle(@Secure Login login,
                                         @PathVariable("feedbackId") Long feedbackId,
                                         @RequestParam("remark") String remark){
        
        Result result = new Result();
        
        try{
            Principal handler = principalService.load(Principal.class, login.getId());
            CourseRoundFeedback feedback = courseRoundService.loadCourseRoundFeedback(feedbackId);
            
            courseRoundService.handle(feedback, remark, handler);
            
            result.success().message("提交成功");
            
        } catch(Exception e){
            
            logger.error("onHandle() error: ", e);
            
            result.fail().message("提交失败");
            
        }
        
        return JsonUtils.toJsonString(result);
        
    }

    /**
     * 
     * @param siteId
     * @param search
     * @return
     */
    @RequestMapping(value = "/search", method = RequestMethod.GET)
    @MenuSetting("submenu-courseround-feedback-management")
    public ModelAndView search() {
        ModelAndView modelAndView = new ModelAndView("user/feedback/courseround-feedback-search");
        
        modelAndView.addObject("today", DateFormatUtils.format(new Date(), "yyyy-MM-dd"));
        
        return modelAndView;
    }

    /**
     * 
     * @param login
     * @param siteId
     * @param search
     * @param page
     * @param request
     * @return
     */
    @RequestMapping(value = "", method = RequestMethod.GET, params = "filter")
    @MenuSetting("submenu-courseround-feedback-management")
    public ModelAndView onSearch(@Secure Login login,
                                 @RequestParam(value = "siteId", required = false) Long siteId,
                                 CourseRoundFeedbackSearch search,
                                 Page page,
                                 HttpServletRequest request) {
        ModelAndView modelAndView = new ModelAndView("user/feedback/courseround-feedback-list");
        
        Site site = null;
        if(siteId != null) {
            site = siteService.load(siteId);
            search.setSite(site);
        }
        
        List<CourseRoundFeedback> feedbacks = new ArrayList<>();
        if(login.isRoot() || login.isAdmin()) {
            feedbacks = courseRoundService.search(search, page);
        } else if(login.isAreaManager() || login.isAreaServer()) {
            Principal principal = principalService.load(Principal.class, login.getId());
            
            List<Site> sites = siteService.listSite(principal);
            
            if(!sites.isEmpty()) {
                search.setSites(sites);
                feedbacks = courseRoundService.search(search, page);
            }
        } else if(login.isSiteManager() || login.isSiteServer()) {
            search.setSite(login.getSite());
            feedbacks = courseRoundService.search(search, page);
        }
        
        modelAndView.addObject("page", page);
        
        modelAndView.addObject("refer", "search");
        modelAndView.addObject("queryString", WebUtils.extractQueryString(request, "page"));
        
        modelAndView.addObject("feedbacks", feedbacks);
        
        return modelAndView;
    }

    /**
     * 
     * @return
     */
    @RequestMapping(value = "/export-view", method = RequestMethod.GET)
    @MenuSetting("submenu-courseround-feedback-management")
    public ModelAndView export() {
        ModelAndView modelAndView = new ModelAndView("user/feedback/courseround-feedback-export");
        
        modelAndView.addObject("today", DateFormatUtils.format(new Date(), "yyyy-MM-dd"));
        
        return modelAndView;
    }

    @RequestMapping(value = "/export", method = RequestMethod.GET)
    public ModelAndView onExport(@Secure Login login,
                                 @RequestParam(value = "siteId", required = false) Long siteId,
                                 CourseRoundFeedbackSearch search) {
        ModelAndView modelAndView = new ModelAndView(new ExcelTemplateView("courseround-feedback-report.xls"));
        
        Site site = null;
        if(siteId != null) {
            site = siteService.load(siteId);
            search.setSite(site);
        }
        
        List<CourseRoundFeedback> feedbacks = new ArrayList<>();
        if(login.isRoot() || login.isAdmin()) {
            feedbacks = courseRoundService.search(search);
        } else if(login.isAreaManager() || login.isAreaServer()) {
            Principal principal = principalService.load(Principal.class, login.getId());
            
            List<Site> sites = siteService.listSite(principal);
            
            if(!sites.isEmpty()) {
                search.setSites(sites);
                feedbacks = courseRoundService.search(search);
            }
        } else if(login.isSiteManager() || login.isSiteServer()) {
            search.setSite(login.getSite());
            feedbacks = courseRoundService.search(search);
        }
        
        modelAndView.addObject("feedbacks", feedbacks);
        modelAndView.addObject("beginDate", search.getBegin() == null ? null : DateFormatUtils.format(search.getBegin(), "yyyy-MM-dd"));
        modelAndView.addObject("endDate", search.getEnd() == null ? null : DateFormatUtils.format(search.getEnd(), "yyyy-MM-dd"));
        modelAndView.addObject("site", search.getSite() == null ? null : search.getSite().getName());
        modelAndView.addObject("name", search.getName());
        modelAndView.addObject("mobile", search.getMobile());
        
        DateFormat fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        modelAndView.addObject("fmt", fmt);
        
        return modelAndView;
    }
}
